package com.jwaoo.chat.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;

import com.dx.as.UI;
import com.dx.as.common.ILoadListener;
import com.dx.as.common.string.StringUtil;
import com.dx.as.upload.DownloadManager;
import com.dx.as.upload.OnDownloadListener;
import com.dx.as.upload.ProgressRequestBody;
import com.dx.as.upload.UploadFile;
import com.jwaoo.chat.ChatConstants;
import com.jwaoo.chat.ChatHelpter;
import com.jwaoo.chat.Message;
import com.jwaoo.chat.R;
import com.jwaoo.chat.attachment.FileAttachment;
import com.jwaoo.chat.data.db.MessageHandler;
import com.jwaoo.chat.session.Extras;
import com.jwaoo.chat.session.ModuleProxy;
import com.jwaoo.chat.session.actions.AVChatAction;
import com.jwaoo.chat.session.actions.BaseAction;
import com.jwaoo.chat.session.actions.Container;
import com.jwaoo.chat.session.actions.ImageAction;
import com.jwaoo.chat.session.actions.SnapChatAction;
import com.jwaoo.chat.session.actions.VideoAction;
import com.jwaoo.chat.session.avchat.AVChatActivity;
import com.jwaoo.chat.session.avchat.AVChatType;
import com.jwaoo.chat.session.input.InputPanel;
import com.jwaoo.chat.session.list.MessageListPanelEx;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 点对点聊天界面
 * <p/>
 */
public class P2PMessageActivity  extends UI {

    protected InputPanel inputPanel;
    protected MessageListPanelEx messageListPanel;
    private MessageReiceiver messageReiceiver;
    private List<Integer> itemIndex = new ArrayList<>();
    public static void start(Context context, int contactId) {
        Intent intent = new Intent();
        intent.putExtra(Extras.EXTRA_ACCOUNT, contactId);
        intent.setClass(context, P2PMessageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_nim_message);
        int friend = getIntent().getIntExtra(Extras.EXTRA_ACCOUNT,0);

        Container container = new Container(this, friend,proxy);
        if (inputPanel == null) {
            inputPanel = new InputPanel(container,getActionList());
        } else {
            inputPanel.reload(container, null);
        }

        if (messageListPanel == null) {
            messageListPanel = new MessageListPanelEx(container,null, false, false);
        } else {
            messageListPanel.reload(container, null);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        messageListPanel.onDestroy();
        if (inputPanel != null) {
            inputPanel.onDestroy();
        }
        ChatHelpter.currentSessionId = 0;
    }

    @Override
    protected void onResume() {
        super.onResume();
        initRecieiver();
//        messageListPanel.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        inputPanel.onPause();
        unregisterReceiver(messageReiceiver);
//        messageListPanel.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    // 操作面板集合
    protected List<BaseAction> getActionList() {
        List<BaseAction> actions = new ArrayList<>();
        actions.add(new ImageAction());
        actions.add(new VideoAction());
        actions.add(new SnapChatAction());
        actions.add(new AVChatAction(AVChatType.AUDIO));
        actions.add(new AVChatAction(AVChatType.VIDEO));
//
//        if (customization != null && customization.actions != null) {
//            actions.addAll(customization.actions);
//        }
        return actions;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        inputPanel.onActivityResult(requestCode, resultCode, data);
//        messageListPanel.onActivityResult(requestCode, resultCode, data);
    }

    private ModuleProxy proxy = new ModuleProxy() {
        @Override
        public boolean sendMessage(Message msg) {
            itemIndex.add(msg.get_id());
//            MessageHandler.getInstace(getApplicationContext()).handlerMessages(MessageHandler.SAVE_MESSAGE,msg);
            messageListPanel.onMsgSend(msg);
//            messageListPanel.
                //sendVideoMessage(msg);
            return true;
        }

        @Override
        public void onInputPanelExpand() {
            messageListPanel.scrollToBottom();
        }

        @Override
        public void shouldCollapseInputPanel() {

        }

        @Override
        public boolean isLongClickEnabled() {
            return false;
        }
    };

    @Override
    public void onBackPressed() {
        if (!inputPanel.hideBottomLayot()){
            finish();
        }
    }

    private void initRecieiver(){
        messageReiceiver = new MessageReiceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ChatConstants.ACTION_MESSAGE);
        registerReceiver(messageReiceiver, intentFilter);
    }
    private class MessageReiceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Message message = (Message) intent.getSerializableExtra(Extras.EXTRA_MESSAGE);
            if (itemIndex.contains(message.get_id())){
                messageListPanel.refreshMessageList(message);
            }else {
                messageListPanel.onMsgSend(message);
                itemIndex.add(message.get_id());
            }
            if (message.getMsgtype() == AVChatType.AUDIO.getValue() || message.getMsgtype() == AVChatType.VIDEO.getValue()){
                AVChatActivity.launch(getApplicationContext(),message.getFriend(),message.getMsgtype(),message.getMsg());
            }
        }
    }

//    private void sendVideoMessage(Message msg){
//        FileAttachment fileAttachment = new FileAttachment();
//        fileAttachment.setLength(msg.getAttachment().getLength());
//        fileAttachment.setPath(msg.getAttachment().getPath());
//
//        //发送语音
//        final Message message = MessageHandler.getInstace(getApplicationContext()).createMessage(ChatConstants.video,fileAttachment);
//        message.set_id(msg.get_id());
//        final Map<String,Object> parm = new HashMap<>();
//        parm.put("type","video");
//        parm.put("as","pub");
//        parm.put("flag","zoom");
//        parm.put("end",".mp4");
//        parm.put("media_type","video/mp4");
//        File file = new File(message.getAttachment().getPath());
//
//        UploadFile.uploadFile(parm,file , new ILoadListener() {
//            @Override
//            public void onResponse(Object response, int flg) {
//                if (response != null){
//                    Map<String,String> result = (Map<String, String>) response;
//                    String url = result.get("path");
//                    message.setAttachState(ChatConstants.transferred);
//                    message.getAttachment().setUrl(url);
//                    MessageHandler.getInstace(getApplicationContext()).sendMessage(message);
//                }
//            }
//
//            @Override
//            public void onFailure(Throwable t) {
//                message.setAttachState(ChatConstants.fail);
//                messageListPanel.refreshMessageList(message);
//            }
//        },new ProgressRequestBody(file,uploadCallbacks));
//    }

}
